package com.tsingteng.cosfun.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.text.Selection;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.AppContext;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.ui.login.LoginActivity;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

/**
 * 描述 : 登录相关工具类
 * 创建人: 肖利.
 * 时间:2018/8/9
 * qq(872179966)
 */

public class LogonUtils {


    /**
     * 隐藏和显示密码
     *
     * @param editText
     * @param isShow
     */
    public static void changePassWord(EditText editText, boolean isShow) {
        if (isShow) {
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        Selection.setSelection(editText.getEditableText(), editText.getEditableText().length());
    }

    /**
     * 获取验证码
     *
     * @param colorRes
     * @param textView
     * @param s
     */
    public static void runTime(@ColorRes int colorRes, final TextView textView, int s) {
        final int color = textView.getCurrentTextColor();
        textView.setTextColor(ContextCompat.getColor(AppContext.getContext(), colorRes));
        new CountDownTimer(1000 * s, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                textView.setText(millisUntilFinished / 1000 + "s");
                textView.setEnabled(false);
            }

            @Override
            public void onFinish() {
                textView.setText("重新获取");
                textView.setEnabled(true);
                textView.setTextColor(color);
                textView.setBackgroundColor(AppContext.getContext().getResources().getColor(R.color.white));
            }
        }.start();
    }

    /**
     * 获取验证码
     *
     * @param textView
     */
    public static void runTime(TextView textView) {
        runTime(R.color.text_color_5, textView, 60);
    }

    /**
     * 标记app是否登录
     *
     * @param isLogin
     */
    public static void setIsLogin(boolean isLogin) {
        SPUtils.init().putBoolean(Config.IS_LOGIN, isLogin);
    }


    /**
     * 是否登录  true  登录  false  未登录
     *
     * @return
     */
    public static boolean getIsLogin() {
        return SPUtils.init().getBoolean(Config.IS_LOGIN, false);
    }


    /**
     * 保存token
     *
     * @param token
     */
    public static void setToken(String token) {
        SPUtils.init().putString("token", token);
    }


    /**
     * 得到token
     *
     * @return
     */
    public static String getToken() {
        return SPUtils.init().getString("token");
    }

    /**
     * 保存mobile
     *
     * @param mobile
     */
    public static void setMobile(String mobile) {
        SPUtils.init().putString("mobile", mobile);
    }


    /**
     * 得到mobile
     *
     * @return
     */
    public static String getMobile() {
        return SPUtils.init().getString("mobile");
    }

    /**
     * 保存is_new_user
     *
     * @param isNewUser
     */
    public static void setIsNewUser(int isNewUser) {
        SPUtils.init().putInt("is_new_user", isNewUser);
    }


    /**
     * 得到is_new_user
     *
     * @return
     */
    public static int getIsNewUser() {
        return SPUtils.init().getInt("is_new_user");
    }


    /**
     * 保存profile_id
     *
     * @param proFildId
     */
    public static void setProFildId(int proFildId) {
        SPUtils.init().putInt("profile_id", proFildId);
    }
    /**
     * 得到profile_id
     *
     * @return
     */
    public static int getProFildId() {
        return SPUtils.init().getInt("profile_id");
    }


    /**
     * 保存cookie
     *
     * @param cookie
     */
    public static void setCookie(String cookie) {
        SPUtils.init().putString("cookie", cookie);
    }


    /**
     * 得到cookie
     *
     * @return
     */
    public static String getCookie() {
        return SPUtils.init().getString("cookie");
    }


    /**
     * 得到name
     *
     * @return
     */
    public static String getNickName() {
        return SPUtils.init().getString("NickName");
    }

    /**
     * 得到name
     *
     * @return
     */
    public static void setNickName(String name) {
        SPUtils.init().putString("NickName", name);
    }

    /**
     * 设置头像
     *
     * @return
     */
    public static void setNickIcon(String icon) {
        SPUtils.init().putString("NickIcon", icon);
    }


    /**
     * 得到头像
     */
    public static String getNickIcon() {
        return SPUtils.init().getString("NickIcon");
    }


    public static boolean isBindType(String type) {
        return SPUtils.init().getBoolean(type, false);
    }

    public static void setBindType(String type, boolean bind) {
        SPUtils.init().putBoolean(type, bind);
    }

    /**
     * 友盟开始授权(登入)
     */
    public static void shareLoginUmeng(Activity activity, SHARE_MEDIA share_media_type, OnLogonListener onLogonListener) {
        UMShareAPI.get(activity).getPlatformInfo(activity, share_media_type, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                Log.e("umengDeleteOauth", "onStart授权开始: ");
                if (onLogonListener != null) {
                    onLogonListener.onStartLogon();
                }
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                //sdk是6.4.5的,但是获取值的时候用的是6.2以前的(access_token)才能获取到值,未知原因
                String uid = map.get("uid");
                String openid = map.get("openid");//微博没有
                String unionid = map.get("unionid");//微博没有
                String access_token = map.get("access_token");
                String refresh_token = map.get("refresh_token");//微信,qq,微博都没有获取到
                String expires_in = map.get("expires_in");
                String name = map.get("name");//名称
                String gender = map.get("gender");//性别
                String iconurl = map.get("iconurl");//头像地址
                Log.e("umengDeleteOauth", "onStart授权完成: " + openid);
                Log.e("umengDeleteOauth", "onStart授权完成: " + unionid);
                Log.e("umengDeleteOauth", "onStart授权完成: " + access_token);
                Log.e("umengDeleteOauth", "onStart授权完成: " + refresh_token);
                Log.e("umengDeleteOauth", "onStart授权完成: " + expires_in);
                Log.e("umengDeleteOauth", "onStart授权完成: " + uid);
                Log.e("umengDeleteOauth", "onStart授权完成: " + name);
                Log.e("umengDeleteOauth", "onStart授权完成: " + gender);
                Log.e("umengDeleteOauth", "onStart授权完成: " + iconurl);
                if (onLogonListener != null) {
                    onLogonListener.onCompleteLogon(share_media_type, openid, access_token, iconurl, name);
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                if (onLogonListener != null) {
                    onLogonListener.onErrorLogon(throwable);
                }
                Log.e("umengDeleteOauth", "onErrori: " + i + "授权失败" + throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                if (onLogonListener != null) {
                    onLogonListener.onCancleLogon();
                }

                Log.e("umengDeleteOauth", "onError: " + "授权取消");
            }
        });
    }

    /**
     * 退出登录
     */
    public static void outLogon() {
        LogonUtils.setToken(null);
        LogonUtils.setIsNewUser(0);
        LogonUtils.setMobile(null);
        LogonUtils.setProFildId(0);
        LogonUtils.setIsAdmin(0);
        LogonUtils.setIsLogin(false);
        AppContext.init();
    }

    /**
     * 友盟取消授权（登入）
     */
    public static void umengDeleteOauth(Activity activity, SHARE_MEDIA share_media_type) {

        UMShareAPI.get(activity).deleteOauth(activity, share_media_type, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                //开始授权
                Log.e("umengDeleteOauth", "onStart: ");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                //取消授权成功 i=1
                Log.e("umengDeleteOauth", "onComplete: ");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                //授权出错
                Log.e("umengDeleteOauth", "onError: ");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                //取消授权
                Log.e("umengDeleteOauth", "onCancel: ");
            }
        });
    }
    /**
     * 保存搜索历史
     *
     * @param his
     */
    public static void setSearchHis(String his) {
        String searchHis = getSearchHistory();
        if (TextUtils.isEmpty(searchHis)) {
            SPUtils.init().putString("history", his);
        }else{
            String searchs="";
            if (searchHis.contains(his)){
                searchs = searchHis.replace(his,"");
            }else{
                searchs = searchHis;
            }
            String search = his+","+searchs;
            SPUtils.init().putString("history", search);
        }
    }
    /**
     * 清除搜索历史
     */
    public static void clearSearchHis(){
        SPUtils.init().putString("history", "");
    }

    /**
     * 得到搜索历史
     *
     * @return
     */
    public static String getSearchHistory() {
        return SPUtils.init().getString("history");
    }

    /**
     * 保存审核管理员
     */
    public static void setIsAdmin(int is_admin){
        SPUtils.init().putInt("is_admin",is_admin);
    }
    /**
     * 获得审核管理员
     */
    public static int getIsAdmin(){
        return SPUtils.init().getInt("is_admin");
    }

    /**
     *
     * @param activity
     * @param isToMain  ture 重新跳到mainactivity 然后跳到相应的界面,false直接关闭登录页
     * @param type  登录之后从主页跳到type页面
     * @return
     */
    public static boolean chckLogon(Activity activity,boolean isToMain,int type) {
        if (!getIsLogin()) {
            Navigate.startLogon(activity, isToMain,type);
            return false;
        }
        return true;
    }

    public static boolean checkLogon(Activity activity, boolean bool,int type) {
        if (!getIsLogin()) {
            Navigate.startLogon(activity, bool,type);
            return false;
        }
        return true;
    }

    public interface OnLogonListener {
        void onStartLogon();

        void onCompleteLogon(SHARE_MEDIA share_media_type, String openid, String access_token, String iconurl, String name);

        void onCancleLogon();

        void onErrorLogon(Throwable throwable);
    }

}
